﻿using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class GameController : MonoBehaviour {
	// === Unity ======================================================================================================
	public GameObject hazard;
	public Vector3 spawnValues;
	public int hazardCount;
	public float spawnWait;
	public float startWait;
	public float waveWait;
	
	public Text scoreText;
	public Text restartText;
	public Text gameOverText;

	private void Start() {
		gameOver = false;
		restart = false;
		restartText.text = "";
		gameOverText.text = "";
		score = 0;
		UpdateScore();
		StartCoroutine(SpawnWaves());
	}

	private void Update() {
		if (restart) {
			if (Input.GetKeyDown(KeyCode.R)) {
				Application.LoadLevel(Application.loadedLevel);
			}
		}
	}

	// === Public =====================================================================================================
	public void AddScore(int newScoreValue) {
		score += newScoreValue;
		UpdateScore();
	}

	public void GameOver() {
		gameOverText.text = "Game Over!";
		gameOver = true;
	}

	// === Private ====================================================================================================
	private bool gameOver;
	private bool restart;
	private int score;

	private IEnumerator SpawnWaves() {
		while (true) {
			yield return new WaitForSeconds(startWait);
			for (int i = 0; i < hazardCount; i++) {
				var spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
				var spawnRotation = Quaternion.identity;
				Instantiate(hazard, spawnPosition, spawnRotation);
				yield return new WaitForSeconds(spawnWait);
			}
			yield return new WaitForSeconds(waveWait);

			if (gameOver) {
				restartText.text = "Press 'R' for Restart";
				restart = true;
				break;
			}
		}
	}

	private void UpdateScore() {
		scoreText.text = "Score: " + score;
	}
}
